using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

namespace GenerativeAgents.Core
{
    /// <summary>
    /// 反思系统
    /// 负责智能体的深度思考、洞察生成和自我反省
    /// </summary>
    public class ReflectionSystem : MonoBehaviour
    {
        [Header("反思配置")]
        [SerializeField] private int maxInsightsPerReflection = 5;
        [SerializeField] private int maxFocusPoints = 3;
        [SerializeField] private float insightImportanceThreshold = 6f;
        [SerializeField] private bool enableReflectionLogging = false;
        
        [Header("反思触发设置")]
        [SerializeField] private int defaultImportanceTrigger = 150;
        [SerializeField] private float reflectionCooldown = 30f; // 分钟
        [SerializeField] private bool allowForceReflection = true;
        
        // 组件引用
        private MemorySystem memorySystem;
        private RetrievalEngine retrievalEngine;
        private ILanguageModel languageModel;
        private InsightGenerator insightGenerator;
        private FocalPointProcessor focalPointProcessor;
        
        // 反思状态
        private DateTime lastReflectionTime;
        private List<string> currentReflectionFoci;
        private List<MemoryNode> currentReflectionMemories;
        private bool isReflecting = false;
        
        // 反思统计
        private int totalReflections = 0;
        private int totalInsightsGenerated = 0;
        private Dictionary<string, int> insightCategories;
        
        // 事件
        public event System.Action<List<string>> OnReflectionStarted;
        public event System.Action<List<MemoryNode>> OnInsightsGenerated;
        public event System.Action OnReflectionCompleted;
        
        private void Awake()
        {
            InitializeReflectionSystem();
        }
        
        private void InitializeReflectionSystem()
        {
            // 获取组件引用
            memorySystem = GetComponent<MemorySystem>();
            retrievalEngine = GetComponent<RetrievalEngine>();
            languageModel = GetComponent<ILanguageModel>();
            
            // 创建子组件
            insightGenerator = new InsightGenerator();
            focalPointProcessor = new FocalPointProcessor();
            
            // 初始化数据结构
            currentReflectionFoci = new List<string>();
            currentReflectionMemories = new List<MemoryNode>();
            insightCategories = new Dictionary<string, int>();
            
            // 初始化统计
            lastReflectionTime = DateTime.Now;
            
            if (enableReflectionLogging)
            {
                Debug.Log("[ReflectionSystem] Reflection system initialized");
            }
        }
        
        /// <summary>
        /// 检查是否应该进行反思
        /// </summary>
        public bool ShouldReflect(ScratchMemory scratchMemory)
        {
            try
            {
                // 检查重要性触发器
                if (scratchMemory.importanceTriggerCurrent <= 0)
                {
                    return true;
                }
                
                // 检查冷却时间
                if ((DateTime.Now - lastReflectionTime).TotalMinutes < reflectionCooldown)
                {
                    return false;
                }
                
                // 检查是否有足够的新记忆
                var recentMemories = memorySystem.AssociativeMemory.GetRecentMemories(TimeSpan.FromHours(2), 10);
                if (recentMemories.Count < 3)
                {
                    return false;
                }
                
                // 检查是否有高重要性事件
                var highImportanceMemories = recentMemories.Where(m => m.poignancy >= 7).ToList();
                if (highImportanceMemories.Count >= 2)
                {
                    return true;
                }
                
                return false;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[ReflectionSystem] Error checking reflection condition: {ex.Message}");
                return false;
            }
        }
        
        /// <summary>
        /// 执行反思过程
        /// </summary>
        public void PerformReflection(ScratchMemory scratchMemory, bool forceReflection = false)
        {
            if (isReflecting && !forceReflection)
            {
                Debug.LogWarning("[ReflectionSystem] Already reflecting, skipping...");
                return;
            }
            
            if (!forceReflection && !ShouldReflect(scratchMemory))
            {
                return;
            }
            
            try
            {
                StartReflection(scratchMemory);
            }
            catch (Exception ex)
            {
                Debug.LogError($"[ReflectionSystem] Error during reflection: {ex.Message}");
                isReflecting = false;
            }
        }
        
        /// <summary>
        /// 开始反思过程
        /// </summary>
        private void StartReflection(ScratchMemory scratchMemory)
        {
            isReflecting = true;
            lastReflectionTime = DateTime.Now;
            
            if (enableReflectionLogging)
            {
                Debug.Log("[ReflectionSystem] Starting reflection process");
            }
            
            // 第一步：生成焦点点
            currentReflectionFoci = GenerateReflectionFoci(scratchMemory);
            OnReflectionStarted?.Invoke(currentReflectionFoci);
            
            // 第二步：检索相关记忆
            currentReflectionMemories = RetrieveReflectionMemories(currentReflectionFoci, scratchMemory.agentName);
            
            // 第三步：生成洞察
            var insights = GenerateInsights(currentReflectionFoci, currentReflectionMemories, scratchMemory);
            
            // 第四步：存储洞察到记忆系统
            StoreInsights(insights, scratchMemory);
            
            // 第五步：更新短期记忆
            UpdateScratchMemory(scratchMemory, insights);
            
            // 完成反思
            CompleteReflection(insights);
        }
        
        /// <summary>
        /// 生成反思焦点
        /// </summary>
        private List<string> GenerateReflectionFoci(ScratchMemory scratchMemory)
        {
            try
            {
                // 获取最近的高重要性记忆
                var recentImportantMemories = memorySystem.AssociativeMemory.GetRecentMemories(TimeSpan.FromHours(4), 15)
                    .Where(m => m.poignancy >= 5)
                    .OrderByDescending(m => m.poignancy)
                    .Take(10)
                    .ToList();
                
                // 使用焦点处理器生成焦点
                var focusPoints = focalPointProcessor.GenerateFocusPoints(recentImportantMemories, maxFocusPoints);
                
                // 添加基于短期记忆的焦点
                if (scratchMemory.currentFocusPoints.Count > 0)
                {
                    focusPoints.AddRange(scratchMemory.currentFocusPoints.Take(2));
                }
                
                // 添加基于最近对话的焦点
                if (scratchMemory.recentConversationPartners.Count > 0)
                {
                    var conversationFocus = $"Recent interactions with {string.Join(", ", scratchMemory.recentConversationPartners.Take(2))}";
                    focusPoints.Add(conversationFocus);
                }
                
                // 去重并限制数量
                var uniqueFocusPoints = focusPoints.Distinct().Take(maxFocusPoints).ToList();
                
                if (enableReflectionLogging)
                {
                    Debug.Log($"[ReflectionSystem] Generated {uniqueFocusPoints.Count} focus points: {string.Join(", ", uniqueFocusPoints)}");
                }
                
                return uniqueFocusPoints;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[ReflectionSystem] Error generating reflection foci: {ex.Message}");
                return new List<string> { "recent experiences", "important events", "relationships" };
            }
        }
        
        /// <summary>
        /// 检索反思相关记忆
        /// </summary>
        private List<MemoryNode> RetrieveReflectionMemories(List<string> focusPoints, string agentName)
        {
            try
            {
                var timeStart = DateTime.Now.AddHours(-6); // 检索过去6小时的记忆
                var reflectionMemories = retrievalEngine.RetrieveForReflection(focusPoints, timeStart, agentName);
                
                // 确保包含一些高重要性记忆
                var highImportanceMemories = memorySystem.AssociativeMemory.GetHighImportanceMemories(7, 5);
                
                // 合并并去重
                var allMemories = reflectionMemories.Concat(highImportanceMemories)
                    .GroupBy(m => m.nodeId)
                    .Select(g => g.First())
                    .OrderByDescending(m => m.poignancy)
                    .Take(20)
                    .ToList();
                
                if (enableReflectionLogging)
                {
                    Debug.Log($"[ReflectionSystem] Retrieved {allMemories.Count} memories for reflection");
                }
                
                return allMemories;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[ReflectionSystem] Error retrieving reflection memories: {ex.Message}");
                return new List<MemoryNode>();
            }
        }
        
        /// <summary>
        /// 生成洞察
        /// </summary>
        private List<MemoryNode> GenerateInsights(List<string> focusPoints, List<MemoryNode> memories, ScratchMemory scratchMemory)
        {
            try
            {
                var insights = new List<MemoryNode>();
                
                foreach (var focusPoint in focusPoints)
                {
                    // 为每个焦点生成洞察
                    var focusMemories = memories.Where(m => 
                        m.content.Contains(focusPoint, StringComparison.OrdinalIgnoreCase) ||
                        m.keywords?.Any(k => k.Contains(focusPoint, StringComparison.OrdinalIgnoreCase)) == true)
                        .ToList();
                    
                    if (focusMemories.Count < 2) continue;
                    
                    var insight = insightGenerator.GenerateInsight(focusPoint, focusMemories, languageModel, scratchMemory);
                    if (insight != null && insight.poignancy >= insightImportanceThreshold)
                    {
                        insights.Add(insight);
                    }
                }
                
                // 生成整体性洞察
                if (memories.Count >= 5)
                {
                    var overallInsight = insightGenerator.GenerateOverallInsight(memories, languageModel, scratchMemory);
                    if (overallInsight != null && overallInsight.poignancy >= insightImportanceThreshold)
                    {
                        insights.Add(overallInsight);
                    }
                }
                
                // 生成社交洞察
                var socialMemories = memories.Where(m => m.participants != null && m.participants.Count > 1).ToList();
                if (socialMemories.Count >= 3)
                {
                    var socialInsight = insightGenerator.GenerateSocialInsight(socialMemories, languageModel, scratchMemory);
                    if (socialInsight != null)
                    {
                        insights.Add(socialInsight);
                    }
                }
                
                // 限制洞察数量
                insights = insights.OrderByDescending(i => i.poignancy).Take(maxInsightsPerReflection).ToList();
                
                totalInsightsGenerated += insights.Count;
                
                if (enableReflectionLogging)
                {
                    Debug.Log($"[ReflectionSystem] Generated {insights.Count} insights");
                    foreach (var insight in insights)
                    {
                        Debug.Log($"  - {insight.content} (Importance: {insight.poignancy})");
                    }
                }
                
                return insights;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[ReflectionSystem] Error generating insights: {ex.Message}");
                return new List<MemoryNode>();
            }
        }
        
        /// <summary>
        /// 存储洞察到记忆系统
        /// </summary>
        private void StoreInsights(List<MemoryNode> insights, ScratchMemory scratchMemory)
        {
            try
            {
                foreach (var insight in insights)
                {
                    // 存储洞察记忆
                    memorySystem.StoreThought(insight.content, insight.poignancy, scratchMemory.currentLocation, scratchMemory.currentLocationName);
                    
                    // 添加到短期记忆的洞察列表
                    scratchMemory.AddInsight(insight.content);
                    
                    // 更新洞察分类统计
                    var category = CategorizeInsight(insight.content);
                    if (!insightCategories.ContainsKey(category))
                    {
                        insightCategories[category] = 0;
                    }
                    insightCategories[category]++;
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[ReflectionSystem] Error storing insights: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 更新短期记忆
        /// </summary>
        private void UpdateScratchMemory(ScratchMemory scratchMemory, List<MemoryNode> insights)
        {
            try
            {
                // 重置重要性触发器
                scratchMemory.ResetImportanceTrigger();
                
                // 清空当前焦点点
                scratchMemory.currentFocusPoints.Clear();
                
                // 如果生成了洞察，可能需要调整心情
                if (insights.Count > 0)
                {
                    var avgImportance = insights.Average(i => i.poignancy);
                    if (avgImportance >= 8)
                    {
                        scratchMemory.UpdateMood("thoughtful", -0.1f); // 深度思考可能消耗能量
                    }
                    else if (avgImportance >= 6)
                    {
                        scratchMemory.UpdateMood("reflective");
                    }
                }
                
                // 更新工作记忆
                scratchMemory.workingMemory["lastReflectionTime"] = DateTime.Now;
                scratchMemory.workingMemory["lastReflectionInsights"] = insights.Count;
            }
            catch (Exception ex)
            {
                Debug.LogError($"[ReflectionSystem] Error updating scratch memory: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 完成反思
        /// </summary>
        private void CompleteReflection(List<MemoryNode> insights)
        {
            try
            {
                totalReflections++;
                isReflecting = false;
                
                OnInsightsGenerated?.Invoke(insights);
                OnReflectionCompleted?.Invoke();
                
                if (enableReflectionLogging)
                {
                    Debug.Log($"[ReflectionSystem] Reflection completed. Generated {insights.Count} insights");
                }
            }
            catch (Exception ex)
            {
                Debug.LogError($"[ReflectionSystem] Error completing reflection: {ex.Message}");
                isReflecting = false;
            }
        }
        
        /// <summary>
        /// 对洞察进行分类
        /// </summary>
        private string CategorizeInsight(string insightContent)
        {
            var lowerContent = insightContent.ToLower();
            
            if (lowerContent.Contains("relationship") || lowerContent.Contains("friend") || lowerContent.Contains("social"))
                return "Social";
            
            if (lowerContent.Contains("work") || lowerContent.Contains("task") || lowerContent.Contains("goal"))
                return "Work";
            
            if (lowerContent.Contains("feeling") || lowerContent.Contains("emotion") || lowerContent.Contains("mood"))
                return "Emotional";
            
            if (lowerContent.Contains("location") || lowerContent.Contains("place") || lowerContent.Contains("environment"))
                return "Environmental";
            
            if (lowerContent.Contains("time") || lowerContent.Contains("schedule") || lowerContent.Contains("routine"))
                return "Temporal";
            
            return "General";
        }
        
        /// <summary>
        /// 强制执行反思
        /// </summary>
        public void ForceReflection(ScratchMemory scratchMemory)
        {
            if (allowForceReflection)
            {
                PerformReflection(scratchMemory, true);
            }
        }
        
        /// <summary>
        /// 获取反思统计信息
        /// </summary>
        public string GetReflectionStats()
        {
            var stats = $"Total Reflections: {totalReflections}, Total Insights: {totalInsightsGenerated}\n";
            stats += $"Last Reflection: {lastReflectionTime:HH:mm}, Is Reflecting: {isReflecting}\n";
            
            if (insightCategories.Count > 0)
            {
                stats += "Insight Categories:\n";
                foreach (var kvp in insightCategories.OrderByDescending(x => x.Value))
                {
                    stats += $"  {kvp.Key}: {kvp.Value}\n";
                }
            }
            
            return stats;
        }
        
        /// <summary>
        /// 设置反思参数
        /// </summary>
        public void SetReflectionParameters(int maxInsights, int maxFocus, float importanceThreshold, float cooldownMinutes)
        {
            maxInsightsPerReflection = maxInsights;
            maxFocusPoints = maxFocus;
            insightImportanceThreshold = importanceThreshold;
            reflectionCooldown = cooldownMinutes;
        }
        
        /// <summary>
        /// 重置反思统计
        /// </summary>
        public void ResetReflectionStats()
        {
            totalReflections = 0;
            totalInsightsGenerated = 0;
            insightCategories.Clear();
        }
        
        /// <summary>
        /// 检查是否正在反思
        /// </summary>
        public bool IsReflecting()
        {
            return isReflecting;
        }
        
        /// <summary>
        /// 获取当前反思焦点
        /// </summary>
        public List<string> GetCurrentReflectionFoci()
        {
            return new List<string>(currentReflectionFoci);
        }
        
        /// <summary>
        /// 获取当前反思记忆
        /// </summary>
        public List<MemoryNode> GetCurrentReflectionMemories()
        {
            return new List<MemoryNode>(currentReflectionMemories);
        }
    }
}